<template>
  <div>
    <!-- 加载状态 -->
    <div v-if="store.isLoading" class="min-h-screen bg-gray-50 flex items-center justify-center">
      <div class="text-center">
        <div class="animate-spin rounded-full h-12 w-12 border-b-2 border-blue-600 mx-auto mb-4"></div>
        <p class="text-gray-600">正在验证登录状态...</p>
      </div>
    </div>
    
    <!-- 认证表单 -->
    <AuthForm v-else-if="!store.isLoggedIn" />
    
    <!-- 主应用 -->
    <div v-else class="min-h-screen bg-gray-50">
      <!-- 顶部导航栏 -->
      <div class="bg-white shadow-sm border-b">
        <div class="px-4 py-3">
          <div class="flex justify-between items-center">
            <div>
              <h1 class="text-lg font-semibold text-gray-900">SmartInput</h1>
              <p class="text-xs text-gray-500">欢迎，{{ store.user?.username }}</p>
            </div>
            <button
              @click="handleLogout"
              class="text-sm text-red-600 hover:text-red-700"
            >
              退出
            </button>
          </div>
        </div>
      </div>

      <!-- 顶部操作栏 -->
      <div class="bg-white border-b px-4 py-3">
        <div class="flex justify-between items-center">
          <div class="flex items-center space-x-4">
            <div class="flex items-center space-x-2">
              <button
                v-if="currentView !== 'voice'"
                @click="currentView = 'voice'"
                class="p-1 text-gray-600 hover:text-gray-800 transition-colors"
              >
                <svg class="w-5 h-5" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                  <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M15 19l-7-7 7-7"></path>
                </svg>
              </button>
              <h2 class="text-lg font-semibold text-gray-900">
                {{ currentView === 'voice' ? '语音输入' : getViewTitle(currentView) }}
              </h2>
            </div>
            <div v-if="currentView === 'voice'" class="flex items-center space-x-1">
              <div :class="[
                'w-2 h-2 rounded-full',
                store.isConnected ? 'bg-green-500' : 'bg-red-500'
              ]"></div>
              <span class="text-xs" :class="store.isConnected ? 'text-green-600' : 'text-red-600'">
                {{ store.isConnected ? '已连接' : '未连接' }}
              </span>
            </div>
          </div>
          
          <!-- 选项菜单 -->
          <div class="relative options-menu">
            <button
              @click="showOptions = !showOptions"
              class="p-2 text-gray-600 hover:text-gray-800 transition-colors"
            >
              <svg class="w-5 h-5" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M12 5v.01M12 12v.01M12 19v.01M12 6a1 1 0 110-2 1 1 0 010 2zm0 7a1 1 0 110-2 1 1 1 0 010 2zm0 7a1 1 0 110-2 1 1 0 010 2z"></path>
              </svg>
            </button>
            
            <!-- 下拉菜单 -->
            <div
              v-if="showOptions"
              class="absolute right-0 mt-2 w-48 bg-white rounded-md shadow-lg border border-gray-200 z-50 options-menu"
            >
              <div class="py-1">
                <button
                  v-for="option in options"
                  :key="option.id"
                  @click="handleOptionClick(option.id)"
                  class="w-full text-left px-4 py-2 text-sm text-gray-700 hover:bg-gray-100 flex items-center space-x-2"
                >
                  <span class="text-lg">{{ option.icon }}</span>
                  <span>{{ option.name }}</span>
                </button>
              </div>
            </div>
          </div>
        </div>
      </div>

      <!-- 内容区域 -->
      <div class="flex-1">
        <VoiceInput v-if="currentView === 'voice'" />
        <VoiceHistory v-else-if="currentView === 'history'" />
        <TestPage v-else-if="currentView === 'test'" />
        <AuthTest v-else-if="currentView === 'auth'" />
        <NetworkTest v-else-if="currentView === 'network'" />
        <MicrophoneTest v-else-if="currentView === 'microphone'" />
        <VoiceSettings v-else-if="currentView === 'voice-settings'" />
      </div>

      <!-- 底部状态栏 -->
      <div class="bg-white border-t px-4 py-2">
        <div class="flex justify-between items-center text-xs text-gray-500">
          <span>设备: {{ store.currentDeviceId || '未设置' }}</span>
          <span>用户: {{ store.user?.username }}</span>
        </div>
      </div>
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref, onMounted } from 'vue';
import { useAppStore } from '@/store';
import { communicationService } from '@/services/communication';
import AuthForm from '@/components/AuthForm.vue';
import VoiceInput from '@/components/VoiceInput.vue';
import VoiceHistory from '@/components/VoiceHistory.vue';
import TestPage from '@/components/TestPage.vue';
import AuthTest from '@/components/AuthTest.vue';
import NetworkTest from '@/components/NetworkTest.vue';
import MicrophoneTest from '@/components/MicrophoneTest.vue';
import VoiceSettings from '@/components/VoiceSettings.vue';

const store = useAppStore();
const currentView = ref('voice');
const showOptions = ref(false);

const options = [
  { id: 'history', name: '历史记录', icon: '📝' },
  { id: 'test', name: '功能测试', icon: '🧪' },
  { id: 'microphone', name: '麦克风测试', icon: '🎤' },
  { id: 'voice-settings', name: '语音设置', icon: '⚙️' },
];

const handleLogout = () => {
  communicationService.disconnect();
  store.logout();
};

const handleOptionClick = (optionId: string) => {
  currentView.value = optionId;
  showOptions.value = false;
};

// 点击外部关闭选项菜单
const closeOptions = () => {
  showOptions.value = false;
};

const getViewTitle = (viewId: string): string => {
  const view = options.find(option => option.id === viewId);
  return view ? view.name : '未知页面';
};

onMounted(async () => {
  // 设置加载状态
  store.setLoading(true);
  
  try {
    // 检查本地存储的认证信息
    const token = localStorage.getItem('smartinput-mobile-token');
    const deviceId = localStorage.getItem('smartinput-mobile-device-id');
    
    if (token && deviceId && store.user) {
      console.log('发现存储的登录信息，尝试自动登录...');
      
      // 验证token有效性
      try {
        const { authAPI } = await import('@/services/api');
        const isValid = await authAPI.validateToken();
        
        if (isValid) {
          console.log('存储的登录信息有效，自动登录成功');
          // 连接WebSocket
          communicationService.connect(token, deviceId);
        } else {
          console.log('存储的登录信息已失效，清除登录状态');
          store.logout();
        }
      } catch (error) {
        console.error('验证登录状态失败:', error);
        store.logout();
      }
    } else {
      console.log('没有存储的登录信息，需要手动登录');
    }
  } catch (error) {
    console.error('初始化应用失败:', error);
  } finally {
    store.setLoading(false);
  }
  
  // 添加点击外部关闭菜单的事件监听
  document.addEventListener('click', (event) => {
    const target = event.target as HTMLElement;
    if (!target.closest('.options-menu')) {
      showOptions.value = false;
    }
  });
  
  // 监听语音设置返回事件
  window.addEventListener('voice-settings-back', () => {
    currentView.value = 'voice';
  });
});
</script>

<style scoped>
/* 全局样式 */
</style> 